<template>
    <div class="app-container ">
        <div class="flex box">
            <el-button type="primary" @click="openAddTaskDialog" class="zdy-btn ">自动降价
                <img class="lines-img" src="@/assets/img/yunji-jiant.png" alt="">
            </el-button>
        </div>
        <div class="zdy-main customTab">
            <el-tabs type="border-card" v-model="actived" @tab-click="tabChange" v-loading="loading">
                <el-tab-pane :label="tab.name" :name="tab.value" v-for="tab in statusList" :key="tab.value">
                    <template v-if="actived == '1'">
                        <el-form :model="queryParams" ref="queryForm" :inline="true" class="zdy-form search-form-new"
                            label-width="68px" @keyup.enter.native="search">
                            <el-form-item label="店铺" prop="tenantId" v-if="checkPermi(['searchTenantID'])">
                                <el-select class="bumen" placeholder="请选择店铺" filterable @change="dianpChange"
                                    v-model="tenantId" clearable>
                                    <el-option v-for="dict in shopList" :key="dict.tenantId" :label="dict.tenantName"
                                        :value="dict.tenantId" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="游戏" prop="gameId">
                                <el-select placeholder="游戏" filterable clearable v-model="queryParams.gameId">
                                    <el-option v-for="dict in getGameLists" :key="dict.id" :label="dict.name"
                                        :value="dict.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item class="btns">
                                <el-button type="primary" icon="el-icon-search" size="mini" @click="searchList"
                                    class="zdy-btn">搜索</el-button>
                                <!-- <el-button icon="el-icon-refresh" plain size="mini" @click="resetQuery"
                                    class="zdy-btn zdy-btn-refresh">重置</el-button> -->
                            </el-form-item>
                        </el-form>
                        <div class="table_box table_box_new">
                            <el-table border :data="tableData.records" style="width: 100%">
                                <el-table-column label="店铺" prop="configName"
                                    v-if="checkPermi(['searchTenantID'])"></el-table-column>
                                <el-table-column label="游戏" prop="gameName" width="160"></el-table-column>
                                <el-table-column label="销售最小金额(¥)" prop="minPrice" width="160"></el-table-column>
                                <el-table-column label="销售最大金额(¥)" prop="maxPrice" width="160"></el-table-column>
                                <el-table-column label="等待时间(天)" prop="waitDays" width="160"></el-table-column>
                                <el-table-column label="降价幅度(%)" prop="reduceExtent" width="160"></el-table-column>
                                <el-table-column label="最低阈值(%)" prop="threshold" width="160"></el-table-column>
                                <el-table-column label="商品数量" prop="2" width="160"></el-table-column>
                                <el-table-column label="是否启用" align="center" width="160">
                                    <template slot-scope="scope">
                                    </template>
                                </el-table-column>
                                 <el-table-column label="创建时间" prop="createTime" width="201"></el-table-column>
                                <el-table-column label="操作" width="180">
                                    <template slot-scope="scope">
                                        <el-button type="text" @click="editTask(scope.row)">编辑</el-button>
                                        <el-button type="text" @click="deleteTask(scope.row)">删除</el-button>

                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="pagination-container" v-if="tableData.total > 0">
                                <el-pagination background @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange" :current-page="queryParams.pageNum"
                                    :page-sizes="[10, 20, 30, 50]" :page-size="queryParams.pageSize"
                                    layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
                                </el-pagination>
                            </div>
                        </div>
                    </template>
                    <template v-if="actived == '2'">
                        <el-form :model="recordForm" ref="recordForm" :inline="true" class="zdy-form search-form-new"
                            label-width="68px" @keyup.enter.native="search">
                            <el-form-item label="游戏" prop="gameId">
                                <el-select placeholder="游戏" filterable clearable v-model="recordForm.gameId">
                                    <el-option v-for="dict in getGameLists" :key="dict.id" :label="dict.name"
                                        :value="dict.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="商品id" prop="goodsId">
                                <el-input placeholder="请输入商品id" v-model="recordForm.goodsId" clearable></el-input>
                            </el-form-item>

                             <el-form-item label="自动降价id" prop="reduceId" label-width="88px">
                                <el-input placeholder="请输入自动降价id" v-model="recordForm.reduceId" clearable></el-input>
                            </el-form-item>
                            <el-form-item class="btns">
                                <el-button type="primary" icon="el-icon-search" size="mini"
                                    @click="getRenovationRecords" class="zdy-btn">搜索</el-button>
                                <el-button icon="el-icon-refresh" plain size="mini" @click="resetRecordQuery"
                                    class="zdy-btn zdy-btn-refresh">重置</el-button>
                            </el-form-item>
                        </el-form>
                        <div class="table_box table_box_new">
                            <el-table border :data="recordTData" style="width: 100%">
                               <el-table-column label="id" prop="id" ></el-table-column>
                                <el-table-column label="店铺" prop="tenant_name" ></el-table-column>
                                <el-table-column label="游戏" prop="gameName" ></el-table-column>
                                <el-table-column label="商品id" prop="goodsId" ></el-table-column>
                                 <el-table-column label="自编码" prop="third_id" ></el-table-column>
                                <el-table-column label="操作类型" prop="type" >
                                    <template slot-scope="scope">
                                        <span>{{ scope.row.type == 1?'自动':'手动' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="修改前价格" prop="before_price" ></el-table-column>
                                <el-table-column label="修改后价格" prop="after_price" ></el-table-column>
                                 <el-table-column label="创建时间" prop="createTime" ></el-table-column>
                            </el-table>
                            <div class="pagination-container" v-if="recordTotal > 0">
                                <el-pagination background @size-change="handleSizeChangeTwo"
                                    @current-change="handleCurrentChangeTwo" :current-page="recordForm.pageNum"
                                    :page-sizes="[10, 20, 30, 50]" :page-size="recordForm.pageSize"
                                    layout="total, sizes, prev, pager, next, jumper" :total="recordTotal">
                                </el-pagination>
                            </div>
                        </div>


                    </template>
                </el-tab-pane>
            </el-tabs>
        </div>
        <!-- 新增弹窗 -->
        <el-dialog title="自动降价" :visible.sync="dialogVisible" width="900px" :close-on-click-modal="false">
            <div class="task-dialog-content">
                <div class="task-info-section">
                    <div class="task-info-title">功能介绍：</div>
                    <div class="task-info-desc">
                        <p>* 自动降价：可一定程度上提升转化率，节约人工成本；</p>
                        <p>* 功能说明：* 为保证良好的生态环境，等待时间不得低于3天，每次降价幅度不得低于1%。</p>
                    </div>
                </div>
                <div class="task-setting-section">
                    <div class="task-setting-title">任务设置：</div>
                    <el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="120px" class="task-form">
                        <el-form-item label="游戏类型" prop="gameId">
                            <el-select v-model="taskForm.gameId" placeholder="请选择游戏类型" style="width: 94%" filterable
                                @change="gameChange">
                                <el-option v-for="game in gameList" :key="game.id" :label="game.name"
                                    :value="game.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <div class="flex">
                        <el-form-item style="flex: 1;" label="价格区间(¥)" prop="minPrice">
                            <el-input v-model="taskForm.minPrice" placeholder="销售最小金额" style="width: 100%"></el-input>
                        </el-form-item>
                        <el-form-item style="flex: 1;" prop="maxPrice" label-width="0px"> <!-- 隐藏label，避免错位 -->
                        <span style="margin: 0 5px;">~</span>
                        <el-input 
                        v-model="taskForm.maxPrice" 
                        placeholder="请输入最大价格"
                        style="width: 86%; "
                        ></el-input>
                    </el-form-item>
</div>

                        <el-form-item label="等待时间(天)" prop="waitDays">
                            <el-input :min="3" v-model="taskForm.waitDays" placeholder="请选择等待时间" style="width: 94%"></el-input>
                        </el-form-item>

                        <el-form-item label="降价幅度(%)" prop="reduceExtent">
                            <el-input v-model="taskForm.reduceExtent" placeholder="请输入降价幅度（%）"
                                style="width: 94%"></el-input>

                        </el-form-item>

                        <el-form-item label="最低阈值(%)" prop="threshold">
                            <el-input v-model="taskForm.threshold" placeholder="请输入最低阈值（%）"
                                style="width: 94%"></el-input>
                            <el-tooltip class="item" effect="dark" content="保证库存最低毛利率，当前场景不支持负利润。" placement="right">
                                <i class="el-icon-question help-icon"></i>
                            </el-tooltip>
                        </el-form-item>


                    </el-form>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" :loading="loading" @click="createTask">{{
                    editJobid ? '修改' : '添加' }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import gameListApi from "@/api/gameConfig/gameList";
import { shopList } from "@/api/system/shopManage";


import { addReducePrice, reducePriceList,putReducePrice, delReducePrice,  reducePriceRecList , changeStatus } from "@/api/tool/gen";
export default {
    data() {
        const validateNumber = (rule, value, callback) => {
            if (!value) return callback(); // 空值由必填验证处理
            // 正则：匹配整数或最多两位小数的数字
            const reg = /^\d+(\.\d{1,2})?$/;
            if (!reg.test(value)) {
                return callback(new Error('请输入（整数或保留两位小数）'));
            }
         
            callback();
        };
        
            const validatewaitDays = (rule, value, callback) => {
            if (!value) return callback(); // 空值由必填验证处理
            if(value < 3) {
                return callback(new Error('请输入大于等于3的等待天数'));
            }
            // 正则：匹配整数或最多两位小数的数字
            const reg = /^\d+(\.\d{1,2})?$/;
            if (!reg.test(value)) {
                return callback(new Error('请输入（整数或保留两位小数）'));
            }
         
            callback();
        };
            
        const validatePriceRange = (rule, value, callback) => {
            const { minPrice, maxPrice } = this.taskForm;
            // 先确保两个值都已输入（必填验证通过后才会触发）
            if (minPrice !== '' && maxPrice !== '') {
                if (Number(maxPrice) < Number(minPrice)) {
                    return callback(new Error('最大价格不能小于最小价格'));
                }
            }
            callback();
        };
        
        return {
            tableData: {
                records: [],
                total: 0
            },
            getGameLists: [],
            recordForm: {
                gameId: '',
                goodsId: '',
              reduceId:'',
                pageSize: 10,
                pageNum: 1
            },
            recordTData: [],
            recordTotal: 0,
            recordTaskLists: [],
            downStateList: [
                { label: "成功", value: "1" },
                { label: "失败", value: "2" },
            ],
            upStateList: [
                { label: "成功", value: "1" },
                { label: "失败", value: "2" },
            ],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                gameId: '',
            },
            loading: false,
            actived: "1",
            dialogVisible: false, // 控制弹窗显示
            taskForm: {
                
                gameId: '', 
                gameName: '',
                minPrice:'',
                maxPrice:'',
                waitDays:'',
                reduceExtent:'',
                threshold:'',
            },
            gameList: [],
            statusList: [
                {
                    name: "自动降价任务",
                    value: "1",
                },
                {
                    name: "自动降价记录",
                    value: "2",
                },
            ],



            timerange: [],
            taskGameList: [],
            shopList: [],
            editJobid: null,
            rules: {
                gameId: [
                    { required: true, message: '请选择游戏', trigger: 'change' }
                ],
                // 最小价格验证规则
                minPrice: [
                    { required: true, message: '请输入最小价格', trigger: 'blur' },
                    { validator: validateNumber, trigger: 'blur' }, // 验证是否为合法数值
                    { validator: validatePriceRange, trigger: 'blur' }
                ],
                // 最大价格验证规则
                maxPrice: [
                    { required: true, message: '请输入最大价格', trigger: 'blur' },
                    { validator: validateNumber, trigger: 'blur' }
                ],
                waitDays: [
                    { required: true, message: '请输入等待天数', trigger: 'blur' },
                    { validator: validatewaitDays, trigger: 'blur' }
                ],
                reduceExtent: [
                    { required: true, message: '请输入降价幅度', trigger: 'blur' },
                    { validator: validateNumber, trigger: 'blur' }
                ],
                threshold: [
                    { required: true, message: '请输入最低阈值', trigger: 'blur' },
                    { validator: validateNumber, trigger: 'blur' }
                ]
            },
            tenantId: ''
        }
    },
    computed: {
        userInfo() {
            return this.$store.getters.userInfo;
        },
    },
    created() {
        this.getAllGamList();
        if (this.userInfo.tenantId == 1) { // 代表是管理员
            this.getShopList()
        } else {
            this.queryParams.tenantId = this.userInfo.tenantId
        }
        this.getTaskList();
    },
    methods: {
        // 验证数值格式：整数或保留两位小数
        validateNumber(rule, value, callback) {
            if (!value) return callback(); // 空值由必填验证处理
            // 正则：匹配整数或最多两位小数的数字
            const reg = /^\d+(\.\d{1,2})?$/;
            if (!reg.test(value)) {
                return callback(new Error('请输入合法数值（整数或保留两位小数）'));
            }
            callback();
        },
        getAllGamList() {
            gameListApi.getGameList().then((res) => {
                this.getGameLists = res.rows;
                this.gameList = res.rows
            });
        },

        async getShopList() {
            let data = {
                pageNum: 1,
                pageSize: 1000
            }
            const res = await shopList(data)
            this.shopList = res.rows
            this.queryParams.tenantId = ''
        },


        dianpChange(val) {
            this.queryParams.tenantId = val
        },

        // 切换标签页
        tabChange(tab) {
            this.actived = tab.name;
            console.log(tab, this.actived);
            this.gameList = []
            if (this.actived === "1") {
                this.queryParams.pageSize = 10
                this.queryParams.pageNum = 1
                this.getTaskList();
            } else {
                this.recordForm.pageSize = 10
                this.recordForm.pageNum = 1

                this.getRenovationRecords();
            }
        },
        resetRecordQuery() {
            this.recordForm = {
                 gameId: '',
                  goodsId: '',
                reduceId:'',
                pageSize: 10,
                pageNum: 1
            },

                this.getRenovationRecords();
        },
        searchList() {
            this.getTaskList()
        },
      
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                gameId: '',
            };
            this.getTaskList();
        },
        getTaskList() {
            this.loading = true;
            reducePriceList(this.queryParams).then(res => {
                this.tableData.records = res.rows;
                this.tableData.total = res.total;
            }).finally(() => {
                this.loading = false;
            });
        },
        gameChange(val) {
            // 根据选中的游戏ID获取游戏名称
            if (Array.isArray(val) && val.length > 0) {
                // 多选情况：获取所有选中游戏的名称
                const selectedGames = this.gameList.filter(game => val.includes(game.id));
                this.taskForm.gameName = selectedGames.map(game => game.name).join(',');
            } else if (val && !Array.isArray(val)) {
                // 单选情况
                const selectedGame = this.gameList.find(game => game.id === val);
                this.taskForm.gameName = selectedGame ? selectedGame.name : '';
            } else {
                // 没有选择游戏
                this.taskForm.gameName = '';
            }
        },


        getRenovationRecords() {
            this.loading = true;

            reducePriceRecList(this.recordForm).then(res => {
                this.recordTData = res.rows
                this.recordTotal = res.total
            }).finally(() => {
                this.loading = false;
            });
        },
        handleSizeChangeTwo(val) {
            this.recordForm.pageSize = val
            this.getRenovationRecords()
        },
        handleCurrentChangeTwo(val) {
            this.recordForm.pageNum = val
            this.getRenovationRecords()
        },
        // 打开新增任务弹窗
        openAddTaskDialog() {
            this.dialogVisible = true;
          
            this.editJobid = null
            // 重置表单
            this.taskForm = {
                gameId: '', 
                gameName: '',
                minPrice:'',
                maxPrice:'',
                waitDays:'',
                reduceExtent:'',
                threshold:'',
            };
        },
        // 创建任务
        createTask() {
            this.loading = true;
            this.$refs.taskForm.validate((valid) => {
                if (valid) {
                    const taskData = {
                        ...this.taskForm,
                    };

                    if (this.editJobid) { //代表是编辑
                        taskData.id = this.editJobid;
                        putReducePrice(taskData).then((res) => {
                            if (res.code == 200) {
                                this.$message.success(res.msg);
                                this.dialogVisible = false;
                                this.getTaskList();
                            } else {
                                this.$message.error('修改失败');
                            }
                        });
                    } else {
                        addReducePrice(taskData).then(res => {
                            if (res.code == 200) {
                                this.$message.success(res.msg);
                                this.dialogVisible = false;
                                this.getTaskList();
                            } else {
                                this.$message.error('添加失败');
                            }
                        })
                    }
                    this.loading = false;

                } else {
                    this.loading = false
                    return false;
                }
            });
        },
        // 编辑任务
        editTask(row) {
            this.taskForm = JSON.parse(JSON.stringify(row))
            this.editJobid = row.id
            this.dialogVisible = true;
        },
      
        // 删除任务
        deleteTask(row) {
            this.$confirm('确认删除吗? 删除后无法恢复', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delReducePrice(row.id).then(res => {
                    this.$message.success(res.msg);
                    this.getTaskList();
                })
            }).catch(() => { });
        },
        handleSizeChange(val) {
            this.queryParams.pageSize = val;
            this.getTaskList();
        },
        handleCurrentChange(val) {
            this.queryParams.pageNum = val;
            this.getTaskList();
        },
        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "暂停";
            this.$modal.confirm(`确认要任务${text}吗？`).then(function () {
                return changeStatus(row);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.header-actions {
    margin-bottom: 20px;
}

.task-dialog-content {
    padding: 0 20px;
}

.task-info-section {
    margin-bottom: 20px;
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
}

.task-info-title {
    font-weight: bold;
    margin-bottom: 10px;
}

.task-info-desc {
    color: #606266;
    line-height: 1.6;

    p {
        margin: 5px 0;
    }
}

.task-setting-section {
    margin-bottom: 20px;
}

.task-setting-title {
    font-weight: bold;
    margin-bottom: 15px;
}

.task-form {
    .el-form-item {
        margin-bottom: 22px;
    }
}

.time-range-checkboxes {
    display: inline-block;
    margin-right: 10px;

    .el-checkbox {
        margin-right: 20px;
    }
}

.help-icon {
    color: #909399;
    margin-left: 5px;
    cursor: pointer;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

/* 表格内操作按钮间距 */
.el-button+.el-button {
    margin-left: 5px;
}

.danger {
    color: rgb(225, 155, 43);
}

.success {
    color: rgb(103, 189, 104);
}


.box {
    align-items: center;
    border-radius: 4px;
    margin-bottom: 10px;

    .flex-l {
        flex: 1;
    }

    .titles {
        color: rgba(51, 51, 51, 1);
        font-size: 18px;
    }

    .tips {
        color: #030C22;
        font-size: 24px;
        text-decoration-line: underline;
        margin: 0px 0 15px;

    }
}

.titles-left-img {
    width: 170px;
}

.titles-right-img {
    width: 200px;
}

.zdy-btn-rent {
    width: 120px;
    font-size: 16px;
    height: 40px;
}

.lines-img {
    margin-top: 2px;
    vertical-align: text-top;
    width: 18px;
    margin-left: 2px;
}
</style>